// 注册 & 登陆服务
package service

import (
	"fmt"
	"pass-config/dao/mapper"
	"pass-config/dao/models"
	"pass-config/middleware"
	"pass-config/util/jwt_util"
	"pass-config/util/md5Util"
	"strings"
)

// 不可泄露！
var salt = "mysalt"

type RegistService struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 检查是否存在相同用户名，存在返回true
func (s *RegistService) IsExistSameUsr() bool {
	usr := mapper.UsrFind(s.Username)
	fmt.Println(usr)
	if usr.UsrId != 0 {
		return true
	}
	return false
}

// 注册用户
func (s *RegistService) Regist() (res map[string]string) {
	res = make(map[string]string)

	// 检查是否存在相同的Usr
	if s.IsExistSameUsr() {
		res["msg"] = "请勿重复注册"
		return
	}

	// 获取雪花生成器，后续该地方需要根据策略输入参数，目前默认0，0
	idWorker, err := middleware.GetIdWorker(0, 0)
	if err != nil {
		res["msg"] = "内部错误"
		return
	}

	// 获取ID
	id := idWorker.GetId()
	usr := &models.PassConfigUsr{
		UsrId:    id,
		Username: s.Username,
		Password: md5Util.Md5Crypt(s.Password, salt),
	}
	err = mapper.UsrInsert(usr)
	if err != nil {
		res["msg"] = "内部错误"
		return
	}
	res["msg"] = "注册成功"
	return
}

// 用户登录
func (s *RegistService) Login() (res map[string]string) {
	res = make(map[string]string)

	// 检查是否存在
	usr := mapper.UsrFind(s.Username)
	fmt.Println(usr.Password, md5Util.Md5Crypt(s.Password, salt))
	if strings.EqualFold(usr.Password, md5Util.Md5Crypt(s.Password, salt)) {
		token, _ := jwt_util.GenerateToken(s.Username)
		res["msg"] = "登录成功"
		res["token"] = token
		return
	}

	res["msg"] = "登录失败，请检查账户或密码"
	res["token"] = ""
	return
}
